import useAsyncLoad from '@/hooks/useAsyncLoad';
import { AssignTaskContext } from '.';
import { Empty } from 'antd';
import React from 'react';
import orgCtrl from '@/ts/controller';
import { InstanceDataModel } from '@/ts/base/model';
import WorkForm from '@/executor/tools/workForm';
import { IAssignTask } from '@/ts/core/work/assign';
import LoadingView from '@/components/Common/Loading';

export interface IProps {
  assignTask: IAssignTask;
}

export function AssignView({ assignTask }: IProps) {
  const belongId = assignTask.metadata.belongId;

  const [loaded, combine] = useAsyncLoad(async () => {
    let detail = await assignTask.loadInstanceDetail(assignTask.metadata.instanceId!);
    if (!detail) {
      detail = await orgCtrl.work.loadInstanceDetail(
        assignTask.metadata.instanceId!,
        belongId,
        belongId,
      );
    }
    if (!detail) {
      return;
    }

    const data: InstanceDataModel = JSON.parse(detail.data || '{}');

    const belong = orgCtrl.user.companys.find((a) => a.id == belongId) || orgCtrl.user;
    return { instance: detail, data, belong };
  });

  if (!loaded) {
    return (
      <div className="loading-page">
        <LoadingView text="信息加载中..." />
      </div>
    );
  }
  if (!combine) {
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <Empty description="找不到关联办事" />
      </div>
    );
  }

  return (
    <AssignTaskContext.Provider value={assignTask}>
      <WorkForm
        allowEdit={false}
        belong={combine.belong}
        nodeId={combine.data.node.id}
        data={combine.data}
      />
    </AssignTaskContext.Provider>
  );
}
